import axios from 'axios';

// 创建axios实例
const service = axios.create({
  baseURL: '/wow',
  timeout: 50000
});

const pyBackService = axios.create({
  baseURL: '/xox',
  timeout: 50000
});

// 请求拦截器 - 添加token
const addTokenInterceptor = config => {
  const token = localStorage.getItem('accessToken');
  if (token) {
    config.headers['access-token'] = token;
  }
  return config;
};

// 响应拦截器 - 处理401错误
const handleUnauthorized = error => {
  if (error.response?.status === 401) {
    localStorage.removeItem('accessToken');
    window.location.href = '/login';
  }
  return Promise.reject(error);
};

const handleError = error =>{
    if (error.response) {
        // 从响应中提取后端返回的错误信息
        const backendError = error.response.data?.message || 
                           error.response.data?.error ||
                           error.message;
        
        // 创建带有后端错误信息的新错误
        const customError = new Error(backendError);
        customError.response = error.response;
        
        return Promise.reject(customError);
      }
      return Promise.reject(error);
}

// 添加拦截器
service.interceptors.request.use(addTokenInterceptor);
service.interceptors.response.use(response => response, handleUnauthorized,handleError);

pyBackService.interceptors.request.use(addTokenInterceptor);
pyBackService.interceptors.response.use(response => response, handleUnauthorized);

// 封装请求方法
const request = (url, method, data) => {
  return service({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: data
  });
};

const pyRequest = (url, method, data) => {
  return pyBackService({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: data
  });
};

// 导出方法
export const getRequest = (url, params) => request(url, 'get', params);
export const postRequest = (url, data) => request(url, 'post', data);
export const putRequest = (url, data) => request(url, 'put', data);
export const deleteRequest = (url) => request(url, 'delete');

export const pyGetRequest = (url, params) => pyRequest(url, 'get', params);
export const pyPostRequest = (url, data) => pyRequest(url, 'post', data);
export const pyPutRequest = (url, data) => pyRequest(url, 'put', data);